/**
* 版权声明：厦门睿商网络科技有限公司 版权所有 违者必究
* 日    期：2020-05-27
*/
package com.rzico.order.controller.admin;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.rzico.annotation.Log;
import com.rzico.base.BaseController;
import com.rzico.base.CommResult;
import com.rzico.basics.entity.*;
import com.rzico.basics.service.EnterpriseService;
import com.rzico.basics.service.ProductService;
import com.rzico.basics.service.ShopService;
import com.rzico.core.entity.SysEmployee;
import com.rzico.core.entity.SysOffice;
import com.rzico.core.entity.SysReport;
import com.rzico.core.entity.SysUser;
import com.rzico.core.service.SysOfficeService;
import com.rzico.core.service.SysReportService;
import com.rzico.core.service.SysSequenceService;
import com.rzico.core.service.SysUserService;
import com.rzico.entity.PageResult;
import com.rzico.entity.Pageable;
import com.rzico.exception.CustomException;
import com.rzico.order.entity.*;
import com.rzico.order.enumx.WarehouseTypeEnum;
import com.rzico.order.service.WxCheckItemService;
import com.rzico.order.service.WxCheckService;
import com.rzico.util.StringUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import net.sf.jasperreports.engine.JRException;
import org.apache.commons.lang3.time.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 盘点单控制层
 *
 * @author Rzico Boot
 * @version 1.0
 * @date 2020-05-27
 */
@Api(description = "盘点单接口")
@RestController
@RequestMapping("/admin/wxCheck")
public class WxCheckAdminController extends BaseController {
    @Value("${rzico.filePath.windows}")
    private String windowsFilePath;

    @Value("${rzico.filePath.linux}")
    private String linuxFilePath;

    @Autowired
    private WxCheckService wxCheckService;

    @Autowired
    private WxCheckItemService wxCheckItemService;

    @Autowired
    private ProductService productService;

    @Autowired
    private EnterpriseService enterpriseService;

    @Autowired
    private SysSequenceService sysSequenceService;

    @Autowired
    private SysOfficeService sysOfficeService;

    @Autowired
    private ShopService shopService;

    @Autowired
    private SysReportService sysReportService;

    @Autowired
    protected SysUserService sysUserService;

    /**
     * 分页查询盘点单
     *
     * @return
    */
    @ApiOperation("分页查询盘点单")
    @GetMapping("/list")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "startDate", value = "开始时间", dataType = "String", paramType = "query") ,
            @ApiImplicitParam(name = "endDate", value = "结束时间", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "shopId", value = "仓库ID", dataType = "Long", paramType = "query"),
            @ApiImplicitParam(name = "productId", value = "商品ID", dataType = "Long", paramType = "query"),
            @ApiImplicitParam(name = "sn", value = "盘点单号", dataType = "String", paramType = "query"),
    })
    public CommResult<WxCheck> list(Date startDate, Date endDate, String sn, Long productId, Long shopId, Pageable pageable) {

        Map<String, Object> params = new HashMap<String, Object>();
        params = buildSortField(params, pageable);
        if (startDate!=null){
            params.put("startDate", DateUtils.truncate(startDate, Calendar.DATE));
        }
        if (endDate!=null){
            params.put("endDate", DateUtils.addMilliseconds(DateUtils.addDays(endDate,1),-1));
        }
        if (StringUtils.isNotEmpty(sn)){
            params.put("sn", sn);
        }

        if (shopId!=null) {
            params.put("shopId",shopId);
        }

        if (null != productId){
            Product product = productService.findById(productId);
            params.put("goodsId", product.getGoodsId());
        }
        params.put("deleted", false);


        Enterprise enterprise = enterpriseService.getCurrent();
        if (enterprise!=null) {
            params.put("enterpriseId", enterprise.getId());
        } else {
            return CommResult.error("没有开通企业");
        }



        //非管理员都启用数据权限
//        SysUser sysUser = sysUserService.getCurrent();
//        if (!sysUserService.isAdmin(sysUser)) {
//            params.put("dataScopeId",sysUser.getId());
//        }


        Page<Object> startPage = PageHelper.startPage(pageable.getPageNum(), pageable.getPageSize());
        List<WxCheck> list = wxCheckService.selectList(params);
        PageResult<WxCheck> pageResult = new PageResult<WxCheck>(list, startPage.getTotal(), pageable);
        return CommResult.success(pageResult);

    }

    /**
     * 查询单条盘点单
     *
     * @return
    */
    @ApiOperation("查询单条盘点单")
    @GetMapping("/find/{id}")
    public CommResult<WxCheck> find(@PathVariable String id) {
        WxCheck result = wxCheckService.findById(id);

        Map<String,Object> data = new HashMap<>();
        data.put("wxCheck",result);

        Map<String,Object> params = new HashMap<>();
        params.put("checkId",result.getId());
        result.setItemList(wxCheckItemService.selectList(params));

        if (result.getOfficeId()!=null) {
            SysOffice sysOffice = sysOfficeService.selectByPrimaryKey(result.getOfficeId());
            if (sysOffice!=null) {
                data.put("officeName", sysOffice.getName());
            }
        } else {
            data.put("officeName", "无");
        }

        if (result.getShopId()!=null) {
            Shop shop = shopService.selectByPrimaryKey(result.getShopId());
            if (shop!=null) {
                data.put("shopName", shop.getName());
            }
        } else {
            data.put("shopName", "无");
        }

        return CommResult.success(data);

    }

    /**
     * 保存盘点单
     *
     * @param wxCheck
     * @return
     */
    @ApiOperation("保存盘点单")
    @PostMapping("/save")
    public CommResult<WxCheck> save(@RequestBody WxCheck wxCheck) {
        Assert.notNull(wxCheck.getShopId(), "门店ID为空");
        Assert.notNull(wxCheck.getItemList(), "盘点明细为空");
        int affectCount = wxCheckService.insertCheck(wxCheck,sysSequenceService.generate("check"));
        if (affectCount <= 0) {
            return CommResult.error();
        }
        WxCheck result = wxCheckService.findById(wxCheck.getId());
        return CommResult.success(result);

    }


    /**
     * 批量删除盘点单
     *
     * @param ids
     * @return
     */
    @Log(desc = "批量删除盘点单", type = Log.LOG_TYPE.DEL)
    @ApiOperation("批量删除盘点单,ids用逗号拼接")
    @PostMapping("/del/{ids}")
    public CommResult<WxCheck> del(@PathVariable String ids) {
        try {
            wxCheckService.deleteByIds(ids.split(","));
        } catch (Exception e) {
            return CommResult.error(e.getMessage());
        }

        return CommResult.success();
    }

    /**
     * 更新盘点单
     *
     * @param wxCheck
     * @return
     */
    @Log(desc = "更新盘点单", type = Log.LOG_TYPE.UPDATE)
    @ApiOperation("更新盘点单")
    @PostMapping("/update")
    public CommResult<WxCheck> update(@RequestBody WxCheck wxCheck) {
        int affectCount = wxCheckService.update(wxCheck);
        if (affectCount <= 0){
            return CommResult.error();
        }
        WxCheck result = wxCheckService.findById(wxCheck.getId());
        return CommResult.success(result);
    }


    /**
     * 盘点确认
     *
     * @param id
     * @return
     */
    @ApiOperation("盘点确认")
    @PostMapping("/confirm/{id}")
    public CommResult<WxCheck> confirm(@PathVariable Long id) {
        Assert.notNull(id, "盘点单编码为空");
        int affectCount = wxCheckService.confirm(id,sysSequenceService.generate("check"));
        if (affectCount <= 0){
            return CommResult.error();
        }
        WxCheck result = wxCheckService.findById(id);
        return CommResult.success(result);
    }


    /**
     * 获取账面库存
     *
     * @return
     */
    @ApiOperation("获取账面库存")
    @PostMapping("/getBookQuantity")
    public CommResult<WxCheckItem> getBookQuantity(Long shopId,Long [] productIds) {
        Assert.notNull(shopId, "仓库ID");
        Assert.notNull(productIds, "产品ID");
        Enterprise enterprise = enterpriseService.getCurrent();

        Map<String,Object> params = new HashMap<>();
        params.put("shopId",shopId);
        params.put("productIds",productIds);
        params.put("enterpriseId", enterprise.getId());
        List<WxCheckItem> wxCheckItemList = wxCheckItemService.selectProductStock(params);
//        List<WxCheckItem> wxCheckItemList = wxCheckItemService.selectList(params);
        if (wxCheckItemList.size()>0) {
            return CommResult.success(wxCheckItemList);
        } else {
            return CommResult.success();
        }
    }


    /**
     * 作废(已确认、未确认可以作废)
     * 已确认的订单，需要判断是否有应收款
     * @param id
     * @return
     */
    @ApiOperation("作废")
    @PostMapping("/cancel/{id}")
    public CommResult<Purchase> cancel(@PathVariable Long id) {
        int affectCount = wxCheckService.cancel(id);
        if (affectCount <= 0){
            return CommResult.error();
        }
        WxCheck result = wxCheckService.findById(id);
        return CommResult.success(result);
    }

    /**
     *  订单打印
     *
     * @param id
     * @return
     */
    @ApiOperation("打印")
    @GetMapping("/print/{id}")
    public void print(HttpServletRequest request, HttpServletResponse response, @PathVariable String id)
            throws ClassNotFoundException, SQLException, JRException, IOException, IllegalAccessException{
        logger.info(">>>>>>>>>>>>>>>>>>>>>>>>>>>订单打印 start<<<<<<<<<<<<<<<<<<<<<<<<<<<");
        Map<String, Object> param = new HashMap<String, Object>();
        WxCheck order = wxCheckService.selectByPrimaryKey(id);
        if (null == order){
            throw new CustomException("盘点单不存在");
        }

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Enterprise enterprise = enterpriseService.selectByPrimaryKey(order.getEnterpriseId());
        if (null == enterprise) {
            throw new CustomException("没有开通企业");
        }
        Shop shop = shopService.selectByPrimaryKey(order.getShopId());
        param.put("shopName", shop.getName());
        param.put("REPORT_NAME","盘点单");
        param.put("COMPANY",enterprise.getName());
        param.put("enterpriseId",enterprise.getId());
        param.put("orderDate", sdf.format(order.getOrderDate()));
        if (StringUtils.isNotEmpty(order.getMemo())){
            param.put("memo", order.getMemo());
        }else{
            param.put("memo", "");
        }
        param.put("orderSn", order.getSn());

        String fileName = enterprise.getMchId()+"_"+order.getSn() + ".jasper";
        //fileName就是sys_report表的id
        SysReport sysReport = sysReportService.selectByPrimaryKey(fileName);

        String filePath = "";
        if (System.getProperty("os.name").contains("Windows")) {
            filePath = windowsFilePath;
        } else if (System.getProperty("os.name").contains("Linux")) {
            filePath = linuxFilePath;
        }
        //检查服务器上是否存在模板
        File file = new File(filePath + File.separator + fileName);
        if (!file.exists()){
            try {
                String url = sysReport == null?"":sysReport.getTemplate();
                sysReportService.fileDownLoad(response, url, filePath, fileName);
            } catch (Exception e){
                logger.info("打印模板下载失败");
                throw new CustomException("打印模板下载失败");
            }
        }

        String reportName = "checkPrint";
        StringBuffer sql = new StringBuffer();
        sql.append(" SELECT product_id, name, sn, ");
        sql.append("    unit, spec, book_quantity, physical_quantity, (physical_quantity - book_quantity) stock_quantity   ");
        sql.append(" FROM wx_check_item");
        sql.append(" WHERE check_id  = "+id );
        File file2 = new File(filePath + File.separator + fileName);
        if (!file2.exists()) {
            //下载之后还不存在，就使用classpath路径的模板
            sysReportService.ReportToPdfBySql(reportName, param, sql.toString(), response);
        }else{
            sysReportService.commReportToPdf(filePath, fileName, param, sql.toString(), response);
        }
    }


    /**
     *  订单打印
     *
     * @param id
     * @return
     */
    @ApiOperation("导出")
    @GetMapping("/export/{id}")
    public void export(HttpServletRequest request, HttpServletResponse response, @PathVariable String id)
            throws ClassNotFoundException, SQLException, JRException, IOException, IllegalAccessException{
        logger.info(">>>>>>>>>>>>>>>>>>>>>>>>>>>订单打印 start<<<<<<<<<<<<<<<<<<<<<<<<<<<");
        Map<String, Object> param = new HashMap<String, Object>();
        WxCheck order = wxCheckService.selectByPrimaryKey(id);
        if (null == order){
            throw new CustomException("盘点单不存在");
        }

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Enterprise enterprise = enterpriseService.selectByPrimaryKey(order.getEnterpriseId());
        if (null == enterprise) {
            throw new CustomException("没有开通企业");
        }
        SysOffice sysOffice = sysOfficeService.findById(order.getOfficeId());
        if (null != sysOffice){
            param.put("officeName",sysOffice.getOfficeName());
        }
        Shop shop = shopService.selectByPrimaryKey(order.getShopId());
        param.put("shopName", shop.getName());
        param.put("REPORT_NAME","盘点单");
        param.put("COMPANY",enterprise.getName());
        param.put("enterpriseId",enterprise.getId());
        param.put("orderDate", sdf.format(order.getOrderDate()));
        if (StringUtils.isNotEmpty(order.getMemo())){
            param.put("memo", order.getMemo());
        }else{
            param.put("memo", "");
        }
        param.put("orderSn", order.getSn());

        String reportName = "checkPrint";
        StringBuffer sql = new StringBuffer();
        sql.append(" SELECT product_id, name, sn, ");
        sql.append("    unit, spec, book_quantity, physical_quantity, (physical_quantity - book_quantity) stock_quantity   ");
        sql.append(" FROM wx_check_item");
        sql.append(" WHERE check_id  = "+id );
        sysReportService.ReportToExcelBySql(reportName, param, sql.toString(),response);
    }
}
